import { useLoad, showToast, useRouter, request } from '@tarojs/taro'
import { useState, useRef, useEffect } from 'react'
import { View, Text, Input, Button } from '@tarojs/components'
import CustomTabBar from '../../components/CustomTabBar'
import './pay.scss'

// 定义交易接口
export interface Transaction {
  id: string
  from: string
  to: string
  amount: number
  timestamp: string
  status: 'pending' | 'completed' | 'failed'
  hash?: string
}

// 简化的交易哈希函数
const calculateTransactionHash = (transaction: Transaction): string => {
  const str = `${transaction.id}${transaction.from}${transaction.to}${transaction.amount}${transaction.timestamp}`
  let hash = 0
  for (let i = 0; i < str.length; i++) {
    const char = str.charCodeAt(i)
    hash = ((hash << 5) - hash) + char
    hash = hash & hash // 转换为32位整数
  }
  return Math.abs(hash).toString(16)
}

// 生成唯一ID
const generateId = (): string => {
  return Date.now().toString(36) + Math.random().toString(36).substr(2)
}

export default function P2PPayment() {
  const router = useRouter()
  const [fromAddress, setFromAddress] = useState('')
  const [toAddress, setToAddress] = useState('')
  const [amount, setAmount] = useState('')
  const [transactions, setTransactions] = useState<Transaction[]>([])
  const [balance, setBalance] = useState(1000)
  const [showTransactionHistory, setShowTransactionHistory] = useState(false)
  const [logs, setLogs] = useState<string[]>([])
  const logEndRef = useRef<HTMLDivElement>(null)

  // 自动滚动到最新日志
  useEffect(() => {
    if (logEndRef.current) {
      logEndRef.current.scrollIntoView({ behavior: 'smooth' })
    }
  }, [logs])

  // 添加日志
  const addLog = (message: string) => {
    setLogs(prev => [...prev, `[${new Date().toLocaleTimeString()}] ${message}`])
  }

  // 清空日志
  const clearLogs = () => {
    setLogs([])
  }

  useLoad(async () => {
    addLog('P2P支付页面已加载')
    try {
      // 生成一个默认的测试地址
      const defaultAddress = await generateTestAddress()
      setFromAddress(defaultAddress)
      
      // 从后端获取余额
      addLog('正在获取账户余额...')
      const res = await request({
        url: `http://localhost:3000/fj/balance/${defaultAddress}`,
        method: 'GET'
      })
      
      if (res.data && res.data.success) {
        setBalance(res.data.balance)
        addLog(`当前账户余额: ${res.data.balance} 元`)
      } else {
        addLog('获取余额失败，使用默认余额')
      }
    } catch (error) {
      addLog(`加载页面时出错: ${error}`)
      showToast({
        title: '加载失败，请检查网络',
        icon: 'none'
      })
    }
  })

  // 发起P2P支付
  const initiatePayment = async () => {
    // 验证输入
    if (!fromAddress || !toAddress || !amount) {
      showToast({
        title: '请填写完整信息',
        icon: 'none'
      })
      return
    }

    const amountNum = parseFloat(amount)
    if (isNaN(amountNum) || amountNum <= 0) {
      showToast({
        title: '请输入有效的金额',
        icon: 'none'
      })
      return
    }

    if (amountNum > balance) {
      showToast({
        title: '余额不足',
        icon: 'none'
      })
      return
    }

    try {
      addLog(`正在发起转账请求: ${amountNum} 元 从 ${fromAddress} 到 ${toAddress}`)
      addLog('正在连接到服务器...')
      
      // 调用后端API进行转账
      const res = await request({
        url: 'http://localhost:3000/fj/transfer',
        method: 'POST',
        data: {
          from: fromAddress,
          to: toAddress,
          amount: amountNum
        }
      })
      
      if (res.data && res.data.success) {
        const transaction = res.data.transaction
        
        addLog(`转账请求已提交，交易ID: ${transaction.id}`)
        addLog(`交易哈希: ${transaction.hash}`)
        addLog('等待服务器处理交易...')
        
        // 更新本地交易列表
        setTransactions(prev => [...prev, transaction])
        
        // 更新本地余额
        setBalance(res.data.newBalance)
        
        addLog('交易处理完成！')
        addLog(`交易状态: 已完成`)
        addLog(`更新后余额: ${res.data.newBalance} 元`)
        
        showToast({
          title: '支付成功',
          icon: 'success'
        })
        
        // 清空金额输入框
        setAmount('')
      } else {
        const errorMessage = res.data?.message || '转账失败'
        addLog(`转账失败: ${errorMessage}`)
        showToast({
          title: errorMessage,
          icon: 'none'
        })
      }
    } catch (error) {
      addLog(`转账时出错: ${error}`)
      showToast({
        title: '网络错误，请重试',
        icon: 'none'
      })
    }
  }

  // 处理交易
  const processTransaction = (transaction: Transaction) => {
    addLog('开始处理交易...')
    addLog('验证交易信息...')
    addLog('确认账户余额...')
    addLog('执行资金转账...')

    // 更新状态
    transaction.status = 'completed'
    
    // 更新交易列表
    setTransactions(prev => [...prev, transaction])
    
    // 更新余额
    const newBalance = balance - transaction.amount
    setBalance(newBalance)
    
    addLog('交易处理完成！')
    addLog(`交易状态: 已完成`)
    addLog(`更新后余额: ${newBalance} 元`)
    
    showToast({
      title: '支付成功',
      icon: 'success'
    })
  }

  // 验证交易记录
  const verifyTransaction = async (transactionId: string) => {
    try {
      addLog(`正在验证交易: ${transactionId}`)
      addLog('正在连接到服务器...')
      
      // 调用后端API验证交易
      const res = await request({
        url: `http://localhost:3000/fj/verify/${transactionId}`,
        method: 'GET'
      })
      
      if (res.data && res.data.success) {
        const { isValid, transaction } = res.data
        
        addLog(`验证哈希值: ${transaction.hash}`)
        
        if (isValid) {
          addLog('交易验证成功！哈希值匹配。')
          showToast({
            title: '交易验证成功',
            icon: 'success'
          })
        } else {
          addLog('交易验证失败！哈希值不匹配。')
          showToast({
            title: '交易验证失败',
            icon: 'none'
          })
        }
      } else {
        const errorMessage = res.data?.message || '验证失败'
        addLog(`验证失败: ${errorMessage}`)
        showToast({
          title: errorMessage,
          icon: 'none'
        })
      }
    } catch (error) {
      addLog(`验证交易时出错: ${error}`)
      showToast({
        title: '网络错误，请重试',
        icon: 'none'
      })
    }
  }

  // 生成测试地址
  const generateTestAddress = async () => {
    try {
      addLog('正在生成测试地址...')
      const res = await request({
        url: 'http://localhost:3000/fj/generate-test-address',
        method: 'GET'
      })
      
      if (res.data && res.data.success) {
        addLog('测试地址生成成功')
        return res.data.address
      } else {
        addLog('测试地址生成失败')
        showToast({
          title: '生成测试地址失败',
          icon: 'none'
        })
        // 生成备用地址
        return `user_${Math.random().toString(36).substr(2, 9)}`
      }
    } catch (error) {
      addLog(`生成测试地址时出错: ${error}`)
      showToast({
        title: '网络错误，使用本地地址',
        icon: 'none'
      })
      // 生成备用地址
      return `user_${Math.random().toString(36).substr(2, 9)}`
    }
  }

  return (
    <View className="payment-container">
      <Text className="title">P2P 支付系统</Text>
      
      {/* 余额显示 */}
      <View className="balance-info">
        <Text className="balance-label">当前余额:</Text>
        <Text className="balance-amount">¥{balance}</Text>
      </View>

      {/* 支付表单 */}
      <View className="payment-form">
        <View className="input-group">
          <Text className="label">付款方地址</Text>
          <Input
            className="input"
            placeholder="输入付款方地址"
            value={fromAddress}
            onInput={e => setFromAddress(e.detail.value)}
          />
          <Button className="helper-btn" onClick={async () => {
            const address = await generateTestAddress()
            setFromAddress(address)
          }}>
            生成测试地址
          </Button>
        </View>

        <View className="input-group">
          <Text className="label">收款方地址</Text>
          <Input
            className="input"
            placeholder="输入收款方地址"
            value={toAddress}
            onInput={e => setToAddress(e.detail.value)}
          />
          <Button className="helper-btn" onClick={async () => {
            const address = await generateTestAddress()
            setToAddress(address)
          }}>
            生成测试地址
          </Button>
        </View>

        <View className="input-group">
          <Text className="label">转账金额 (元)</Text>
          <Input
            className="input"
            placeholder="输入转账金额"
            value={amount}
            onInput={e => setAmount(e.detail.value)}
            type="digit"
          />
        </View>

        <View className="button-group">
          <Button className="primary-btn" onClick={initiatePayment}>
            发起转账
          </Button>
          <Button className="secondary-btn" onClick={async () => {
            if (!showTransactionHistory && fromAddress) {
              // 切换到显示状态时，从后端获取交易历史
              try {
                addLog('正在获取交易历史...')
                const res = await request({
                  url: `http://localhost:3000/fj/transactions/${fromAddress}`,
                  method: 'GET'
                })
                
                if (res.data && res.data.success) {
                  setTransactions(res.data.transactions)
                  addLog(`获取到 ${res.data.transactions.length} 条交易记录`)
                }
              } catch (error) {
                addLog(`获取交易历史时出错: ${error}`)
                showToast({
                  title: '获取交易历史失败',
                  icon: 'none'
                })
              }
            }
            setShowTransactionHistory(!showTransactionHistory)
          }}>
            {showTransactionHistory ? '隐藏' : '查看'}交易记录
          </Button>
        </View>
      </View>

      {/* 交易历史 */}
      {showTransactionHistory && (
        <View className="transaction-history">
          <Text className="subtitle">交易记录</Text>
          {transactions.length === 0 ? (
            <Text className="empty-message">暂无交易记录</Text>
          ) : (
            transactions.map(transaction => (
              <View key={transaction.id} className="transaction-item">
                <View className="transaction-details">
                  <Text className="transaction-id">ID: {transaction.id.substring(0, 10)}...</Text>
                  <Text className="transaction-amount">¥{transaction.amount}</Text>
                  <Text className={`transaction-status status-${transaction.status}`}>
                    {transaction.status === 'completed' ? '成功' : transaction.status === 'failed' ? '失败' : '处理中'}
                  </Text>
                </View>
                <View className="transaction-info">
                  <Text>从: {transaction.from.substring(0, 8)}...</Text>
                  <Text>到: {transaction.to.substring(0, 8)}...</Text>
                  <Text>时间: {new Date(transaction.timestamp).toLocaleString()}</Text>
                </View>
                <Button 
                  className="verify-btn"
                  onClick={() => verifyTransaction(transaction.id)}
                >
                  验证交易
                </Button>
              </View>
            ))
          )}
        </View>
      )}

      {/* 系统日志 */}
      <View className="logs-section">
        <View className="logs-header">
          <Text className="subtitle">系统日志</Text>
          <Button className="clear-log-btn" onClick={clearLogs}>
            清空日志
          </Button>
        </View>
        <View className="logs-container">
          {logs.map((log, index) => (
            <Text key={index} className="log-entry">{log}</Text>
          ))}
          <div ref={logEndRef} />
        </View>
      </View>
    
    {/* 自定义TabBar */}
    <CustomTabBar />
  </View>
  )
}